import API from '@/api/index'
import useChats from '@/stores/chats'
import useUserStore from '@/stores/user'
import useLoadingStore from '@/stores/loading'

function useHook(scrollToBottom) {
  const { sessionId } = useUserStore()
  const loading = useLoadingStore()

  const talking = ref(false)
  const chats = useChats()
  // const messages = ref([])

  const messageList = computed(() => chats.messages.filter((v) => v.role !== 'system'))

  async function send(content) {
    // talking.value = true
    loading.open()
    chats.addMessage(content)

    const _defaultParams = {
      model: "gpt-3.5-turbo",
      stream: true,
      messages: chats.messages,
      sessionId
    }
    const params = chats.chat.aitype ? { ..._defaultParams, aitype: chats.chat.aitype } : _defaultParams

    let { status, data, message, abortCtrl } = await API.streamai(params)
    // let { status, data, message, abortCtrl } = await API.chatgpt(params) // 普通方式

    // return console.log(11, data)

    loading.setAbortCtrl(abortCtrl)

    // 监听abort
    // abortCtrl.signal.addEventListener('abort', () => {
    //   talking.value = false
    // })

    if (status === 0 && data) {
      // 普通方式
      // if(data.data.url) {
      //   appendLastMessageContent(`<img src="${data.data.url}" />`)
      // } else {
      //   await getMessage(data.data.message)
      // }

      // steam模式
      if (typeof data === 'string') {
        await getMessage_steam(data)
      } else {
        console.log(11, data)
        const {content, url, source} = data.data
        if(content) {
          await getMessage(content)
          appendLastMessageContent(source)
        } else if(url) {
          appendLastMessageContent(`<img src="${url}" />`)
        }
      }

    } else {
      const { stack } = message
      appendLastMessageContent(stack || message)
    }

    // talking.value = false
    loading.close()
  }

  async function getMessage(message) {
    for(let i = 0; i < message.length; i ++) {
      await messageAnimate(message[i])
    }
  }

  async function messageAnimate(content) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(appendLastMessageContent(content))
      }, 100 / 6)
    })
  }

  async function getMessage_steam(data) {

    // const dataList = data.match(/(?<=data: )\s*({.*?}}])/g)
    const dataList = data.match(/data: \s*({.*?}}])/g)
                                     
    console.log(11, data, dataList)

    for (let i in dataList) {
      const v = dataList[i]
      // const json = JSON.parse(`${v}}`)
      const json = JSON.parse(`${v.substr(6)}}`)
      const content = json.choices[0].delta.content ?? ''
      await animateAppend(content)
    }

    // await getMessage_steam(data)
  }

  async function getMessageForSteam(reader) {
    const decoder = new TextDecoder("utf-8")
    const res = await reader.read()
    const { done, value } = res
    if (done) {
      reader.closed
      return
    }
    console.log('--------------')
    const str = decoder.decode(value)
    // const dataList = str.match(/(?<=data: )\s*({.*?}}])/g)
    const dataList = str.match(/data: \s*({.*?}}])/g) // 适配safari
                               
                               

    for (let i in dataList) {
      const v = dataList[i]
      // const json = JSON.parse(`${v}}`)
      const json = JSON.parse(`${v.substr(6)}}`)
      const content = json.choices[0].delta.content ?? ''
      console.log('stream:', content)
      await animateAppend(content)
    }

    await getMessage(reader)
  }

  function animateAppend(content) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(appendLastMessageContent(content))
      }, 100 / 6)
    })
  }

  function appendLastMessageContent(content) {
    chats.messages[chats.messages.length - 1].content += content

    nextTick(scrollToBottom)
  }

  return {
    messageList,
    // talking,
    send,
  }

}


export default useHook